package idv.arthur.JCraft;

import java.io.File;
import java.util.Vector;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class RemoveDir {
	
    
    static Session session = null;
    static ChannelSftp sftpChannel = null;
    static String dir = "/var/www/svn/Arthur";
    
	public static void main(String[] args) throws SftpException, JSchException {
		JSch jsch = new JSch();
		JSch.setConfig("StrictHostKeyChecking", "no");
		
		String id = "root";
		String url = "10.144.97.99";
		String pwd = "arthur7382";
		
		
		session = jsch.getSession(id, url);
		session.setPassword( pwd );
		session.connect();
		sftpChannel = (ChannelSftp) session.openChannel("sftp");
		sftpChannel.connect();
		lsFolderRemove(dir);
		
		//sftpChannel.rmdir(dir);
		sftpChannel.disconnect(); 
	}
	
	private static void lsFolderRemove(String dir) {
		try {
		    sftpChannel.cd(dir);
		    Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(dir); // List source directory structure.
		    for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
		        if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
		            sftpChannel.rm(dir + "/" + oListItem.getFilename()); // Remove file.
		        } else if (!".".equals(oListItem.getFilename())) { // If it is a subdir.
		            try {
		                sftpChannel.rmdir(dir + "/" + oListItem.getFilename());  // Try removing subdir.
		            } catch (Exception e) { // If subdir is not empty and error occurs.
		                lsFolderRemove(dir + "/" + oListItem.getFilename()); // Do lsFolderRemove on this subdir to enter it and clear its contents.
		            }
		        }
		    }
		    sftpChannel.rmdir(dir); // Finally remove the required dir.
		} catch (SftpException sftpException) {
			sftpException.printStackTrace();
		    System.out.println("Removing " + dir + " failed. It may be already deleted.");
		}
	}
	
	
}
